<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物资编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="取消操作人" prop="canceledBy">
        <el-input
          v-model="queryParams.canceledBy"
          placeholder="请输入取消操作人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="${comment}" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择${comment}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="${comment}" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择${comment}">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['SysModel:SysModelFeeding:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['SysModel:SysModelFeeding:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['SysModel:SysModelFeeding:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['SysModel:SysModelFeeding:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysModelFeedingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="养殖模块id" align="center" prop="id" /> -->
       <el-table-column label="模板编号" align="center" prop="modelName" />
      <el-table-column label="类型" align="center" prop="category" />
      <el-table-column label="物资名称" align="center" prop="materialName" />
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <el-table-column label="物资编码" align="center" prop="materialCode" />
      <!-- <el-table-column label="取消操作人" align="center" prop="canceledBy" />
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="${comment}" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="${comment}" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysModel:SysModelFeeding:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysModel:SysModelFeeding:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改喂养模板对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form-item label="模板编号" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模板编号" />
        </el-form-item>
      <el-form ref="SysModelFeedingRef" :model="form" :rules="rules" label-width="80px">
        <!-- 类型（即类别） -->
        <el-form-item label="类型" prop="category">
          <el-select v-model="form.category" placeholder="请选择类型" @change="handleCategoryChange" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 物资名称 -->
        <el-form-item label="物资名称" prop="materialName">
          <el-select
            v-model="form.materialName"
            placeholder="请选择物资名称"
            @change="handleNameChange"
            :disabled="!form.category"
            clearable
          >
            <el-option
              v-for="item in nameOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 批次号 -->
        <el-form-item label="批次号" prop="batchNumber">
          <el-select
            v-model="form.batchNumber"
            placeholder="请选择批次号"
            @change="handleBatchChange"
            :disabled="!form.materialName"
            clearable
          >
            <el-option
              v-for="item in batchOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 物资编码 -->
        <el-form-item label="物资编码" prop="materialCode">
          <el-select
            v-model="form.materialCode"
            placeholder="请选择物资编码"
            @change="handleCodeChange"
            :disabled="!form.batchNumber"
            clearable
          >
            <el-option
              v-for="item in codeOptions"
              :key="item.materialCode"
              :label="item.materialCode"
              :value="item.materialCode"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="取消操作人" prop="canceledBy">
          <el-input v-model="form.canceledBy" placeholder="请输入取消操作人" />
        </el-form-item>
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="${comment}" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择${comment}">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="${comment}" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择${comment}">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysModelFeeding">
import { listSysModelFeeding, getSysModelFeeding, delSysModelFeeding, addSysModelFeeding, updateSysModelFeeding } from "@/api/SysModel/SysModelFeeding"
import {listCategories,listNamesByCategory,fetchBatchRecords,listBatches} from "@/api/SysFeedingRecords/material"
const { proxy } = getCurrentInstance()

const SysModelFeedingList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 下拉选项
const categoryOptions = ref([])  // 类别
const nameOptions = ref([])      // 名称
const batchOptions = ref([])     // 批次号
const codeOptions = ref([])      // 物资编码（带 id）

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    category: null,
    materialName: null,
    batchNumber: null,
    materialCode: null,
    canceledBy: null,
    createdBy: null,
    createdAt: null,
    updatedAt: null,
    modelName: null,
  },
  rules: {
    createdBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/**
 * 通用接口响应处理函数
 * 适配后端常见的响应格式：{code: 200, msg: "success", data: ...}
 */
const handleResponse = (response) => {
  // 检查是否为标准响应格式
  if (response && typeof response === 'object') {
    // 如果有code字段且不为200，视为错误
    if ('code' in response && response.code !== 200) {
      throw new Error(response.msg || '接口请求失败');
    }
    // 返回数据部分，优先取data字段
    return response.data !== undefined ? response.data : response;
  }
  return response;
};

/** 查询喂养模板列表 */
function getList() {
  loading.value = true
  listSysModelFeeding(queryParams.value).then(response => {
    SysModelFeedingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    category: null,
    materialName: null,
    batchNumber: null,
    materialCode: null,
    canceledBy: null,
    createdBy: null,
    createdAt: null,
    updatedAt: null,
    inventoryId: null,
    modelName: null,
  }
  proxy.resetForm("SysModelFeedingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加喂养模板"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSysModelFeeding(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改喂养模板"
  })
}

async function loadCategories() {
  try {
    const response = await listCategories();
    const data = handleResponse(response); // 复用 handleResponse
    categoryOptions.value = Array.isArray(data) ? data : [];
  } catch (err) {
    proxy.$modal.msgError("加载类别失败：" + err.message);
  }
}

function handleCategoryChange(category) {
  form.value.materialName = '';
  form.value.batchNumber = '';
  form.value.materialCode = '';
  nameOptions.value = [];
  batchOptions.value = [];
  codeOptions.value = [];

  if (!category) return;

  listNamesByCategory(category)
    .then(res => {
      const data = handleResponse(res);
      nameOptions.value = Array.isArray(data) ? data : [];
    })
    .catch(err => proxy.$modal.msgError("加载名称失败：" + err.message));
}

async function handleNameChange(name) {
  form.value.batchNumber = '';
  form.value.materialCode = '';
  batchOptions.value = [];
  codeOptions.value = [];

  if (!form.value.category || !name) return;

  try {
    const res = await fetchBatchRecords(form.value.category, name);
    const batches = handleResponse(res);
    batchOptions.value = Array.isArray(batches)
      ? batches.map(b => b.batchNumber || b)
      : [];
  } catch (err) {
    proxy.$modal.msgError("加载批次号失败：" + err.message);
  }
}

async function handleBatchChange(batchNumber) {
  form.value.materialCode = '';
  codeOptions.value = [];

  if (!form.value.category || !form.value.materialName || !batchNumber) return;

  try {
    const res = await listBatches(form.value.category, form.value.materialName, batchNumber);
    const details = handleResponse(res);
    if (Array.isArray(details)) {
      codeOptions.value = details;
      // 可自动选第一个
      if (details.length === 1) {
        form.value.materialCode = details[0].materialCode;
      }
    }
  } catch (err) {
    proxy.$modal.msgError("加载物资编码失败：" + err.message);
  }
}

function handleCodeChange(materialCode) {
  const selected = codeOptions.value.find(item => item.materialCode === materialCode);
  form.value.inventoryId = selected ? selected.id : null;
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysModelFeedingRef"].validate(valid => {
    if (valid) {
      // 构造 payload，确保 inventoryId 被包含（即使 form.value 中已有，也可显式保留）
      const payload = {
        ...form.value,
        //inventoryId: form.value.inventoryId // 显式确保提交该字段
        category: form.value.category,
        materialName: form.value.materialName,
        batchNumber: form.value.batchNumber,
        materialCode: form.value.materialCode,
      };

      if (form.value.id != null) {
        updateSysModelFeeding(payload).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSysModelFeeding(payload).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除喂养模板编号为"' + _ids + '"的数据项？').then(function() {
    return delSysModelFeeding(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysModel/SysModelFeeding/export', {
    ...queryParams.value
  }, `SysModelFeeding_${new Date().getTime()}.xlsx`)
}
onMounted(() => {
  loadCategories() // 加载类别
  getList()
})
getList()
</script>
